﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Lime49;
using Lime49.UI;
using LockCrypt.Core;
using LockCrypt.Properties;
using Microsoft.Win32;
using WPFLocalizeExtension.Engine;
using LockCrypt.DAL;

namespace LockCrypt {
    /// <summary>
    /// Options dialog.
    /// </summary>
    public partial class WinOptions : Window {
        /// <summary>
        /// Initializes a new <see cref="WinOptions"/> Window.
        /// </summary>
        public WinOptions() {
            InitializeComponent();
            cboLanguage.ItemsSource = Constants.Languages;
            cboEncryption.ItemsSource = EnumBinder.EnumHelper.ToList<string>(typeof(EncryptionProviders));
            cboCloseAction.ItemsSource = new Dictionary<bool, string>() {
                { true, I18nUtils.GetString("Strings", "LockCloseTheDatabase")},
                { false, I18nUtils.GetString("Strings", "PromptForPassword")}
            };
            //autotypeHotkeyMapper.ShortcutKey = gesture;
        }

        /// <summary>
        /// Saves applicable settings to static variables and returns a DialogResult of true.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void Save(object sender, ExecutedRoutedEventArgs e) {
            if(!ValidateSettings()) {
                return;
            }
            try {
                if(Settings.Default.AutoOpenOnStartup) {
                    Settings.Default.DatabaseConnectionString = dbSelector.Provider.ConnectionString;
                }
                RegistryKey autoStartKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.WriteKey | System.Security.AccessControl.RegistryRights.Delete);
                try {
                    if(Settings.Default.AutoStart) {
                        string applicationPath = System.IO.Path.Combine(Utils.GetApplicationPath(), "LockCrypt.exe");
                        autoStartKey.SetValue("LockCrypt", applicationPath);
                    } else {
                        autoStartKey.DeleteValue("LockCrypt", false);
                    }
                } catch(UnauthorizedAccessException unEx) {
                    DialogBox.ShowAlert(this, I18nUtils.GetString("Errors", "PermissionAddRegistryDenied"), I18nUtils.GetString("Strings", "AutoStart"));
                    Console.WriteLine("opts63: "+unEx.Message);
                } catch(System.Security.SecurityException sEx) {
                    DialogBox.ShowAlert(this, I18nUtils.GetString("Errors", "PermissionAddRegistryDenied"), I18nUtils.GetString("Strings", "AutoStart"));
                    Console.WriteLine("opts63: " + sEx.Message);
                }
                Settings.Default.Save();
                IDbProvider currentProvider = DalConfigurationManager.Provider;
                WPFConfigurationManager.Configure();
                DalConfigurationManager.Provider = currentProvider;// preserve the current file

                if(Settings.Default.Language != LocalizeDictionary.Instance.Culture.Name) {
                    LocalizeDictionary.Instance.Culture = CultureInfo.GetCultureInfo(Settings.Default.Language);
                }
                DialogResult = true;
            } catch(Exception ex) {
                DialogBox.ShowAlert(this, ex.Message, I18nUtils.GetString("Errors", "Error"));
            }
        }

        /// <summary>
        /// Closes the window, cancelling changes.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void CloseWindow(object sender, ExecutedRoutedEventArgs e) {
            Settings.Default.Reload();
            DialogResult = false;
        }

        /// <summary>
        /// Validates the settings provided.
        /// </summary>
        /// <returns><c>true</c> if the settings are valid, otherwise <c>false</c>.</returns>
        private bool ValidateSettings() {
            bool valid = true;
            if(chkAutoOpen.IsChecked == true && !dbSelector.ValidateSettings()) {
                tabDatabase.IsSelected = true;
                tabDatabase.Focus();
                valid = false;
            }
            return valid;
        }
    }
}
